package apobates.gui.formatter.reader;

import org.mozilla.universalchardet.ReaderFactory;
import java.io.*;

/**
 * Json文件读取器
 */
public record JsonFileReader(String path, String charsetName) {

    public String getPath() {
        return path;
    }

    public String getCharsetName() {
        return charsetName;
    }

    public String read()throws IOException{
        if(null == charsetName || charsetName.isEmpty()){
            return detectEncodeRead();
        }
        return specialEncodeRead();
    }

    /**
     *
     * @return
     * @throws IOException
     */
    private String detectEncodeRead()throws IOException {
        File file = new File(getPath());
        try(BufferedReader reader = ReaderFactory.createBufferedReader(file)){
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
            return content.toString();
        }
    }

    /**
     *
     * @return
     * @throws IOException
     */
    private String specialEncodeRead()throws IOException {
        try(FileInputStream inputStream = new FileInputStream(getPath());
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, getCharsetName()))){
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
                content.append(System.lineSeparator());
            }
            return content.toString();
        }
    }

    public static class Builder{
        private final String path;
        private String charsetName = null;

        private Builder(String path){
            this.path = path;
        }
        public static Builder create(String path){
            return new Builder(path);
        }
        public Builder charset(String charsetName){
            this.charsetName = charsetName;
            return this;
        }
        public JsonFileReader build(){
            return new JsonFileReader(this.path, this.charsetName);
        }
    }
}
